package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Consumer {

	public static void main(String[] args) throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		ConnectionFactory factory = (ConnectionFactory) context
				.getBean("targetConnectionFactory");
		Destination queue = (Destination) context.getBean("queueDestination");
		Connection con = factory.createConnection();
		con.start();

		Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		MessageConsumer consumer = session.createConsumer(queue);
		consumer.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message arg0) {

				TextMessage msg = (TextMessage) arg0;
				try {
					String s1 = msg.getText();
					JSONObject json = new JSONObject(s1);
					System.out.println(json.get("ip"));

					// for testing write log
					FileWriter fw = null;
					File f = new File("consumer.log");

					try {
						if (!f.exists()) {
							f.createNewFile();
						}
						fw = new FileWriter(f,true);
						BufferedWriter out = new BufferedWriter(fw);
						out.write("\r\n" + s1, 0, s1.length() - 1);
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("end");

				

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

		// consumer.close();
		// session.close();
		// con.close();
	}

}
